package com.ruoyi.system.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.Stop;
import com.ruoyi.system.domain.TExternalPowerSupply;
import com.ruoyi.system.service.IExitService;
import com.ruoyi.system.service.ITotalSiteService;
import com.ruoyi.system.utils.TransData;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Lists;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.TTingdianTuifu;
import com.ruoyi.system.service.ITTingdianTuifuService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 停电且退服（测试一下，确认后删除此注释）Controller
 * 
 * @author ruoyi
 * @date 2021-12-10
 */
@RestController
@RequestMapping("/tietasystem/tuifu")
public class TTingdianTuifuController extends BaseController
{
    @Autowired
    private ITTingdianTuifuService tTingdianTuifuService;

    /**
     * 查询停电且退服（测试一下，确认后删除此注释）列表
     */
    @PreAuthorize("@ss.hasPermi('tietasystem:tuifu:list')")
    @GetMapping("/list")
    public TableDataInfo list(TTingdianTuifu tTingdianTuifu)
    {
        String depName = getLoginUser().getUser().getDept().getDeptName();
        String userName = getLoginUser().getUser().getUserName();
        String city = ("辽宁省".equals(TransData.transCityMap(depName)) || "admin".equals(userName)) ? null : TransData.transCityMap(depName);
        if(city == null) {
        	city = tTingdianTuifu.getCity();
        }
        List<TTingdianTuifu> list;
        if(tTingdianTuifu != null){
        	tTingdianTuifu.setCity(city);
            startPage();
            list = tTingdianTuifuService.selectTTingdianTuifuList(tTingdianTuifu);
        } else {
        	list = Lists.newArrayList();
        }
        
        return getDataTable(list);
    }

    /**
     * 导出停电且退服（测试一下，确认后删除此注释）列表
     */
    @PreAuthorize("@ss.hasPermi('tietasystem:tuifu:export')")
    @Log(title = "停电且退服（测试一下，确认后删除此注释）", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TTingdianTuifu tTingdianTuifu)
    {
        //获取用户所属公司
        Long deptid = getDeptId();
        List<TTingdianTuifu> list = tTingdianTuifuService.selectTTingdianTuifuList(tTingdianTuifu);
        ExcelUtil<TTingdianTuifu> util = new ExcelUtil<TTingdianTuifu>(TTingdianTuifu.class);
        String depName = getLoginUser().getUser().getDept().getDeptName();
        String userName = getLoginUser().getUser().getUserName();
        if(!(depName.contains("辽宁省") || "admin".equals(userName))){
            List<TTingdianTuifu> list1 = list.stream().filter((t)->{
                return depName.contains(t.getCity());
            }).collect(Collectors.toList());
            return util.exportExcel(list1, "停电且退服");
        }
        return util.exportExcel(list, "停电且退服");
    }

    /**
     * 获取停电且退服（测试一下，确认后删除此注释）详细信息
     */
    @PreAuthorize("@ss.hasPermi('tietasystem:tuifu:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return AjaxResult.success(tTingdianTuifuService.selectTTingdianTuifuById(id));
    }

    /**
     * 新增停电且退服（测试一下，确认后删除此注释）
     */
    @PreAuthorize("@ss.hasPermi('system:tuifu:add')")
    @Log(title = "停电且退服（测试一下，确认后删除此注释）", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TTingdianTuifu tTingdianTuifu)
    {
        tTingdianTuifu.setVersion(tTingdianTuifu.getVersion().toString());
        tTingdianTuifu.setCreateBy(getUsername());
        tTingdianTuifu.setUpdateBy(getUsername());
        return toAjax(tTingdianTuifuService.insertTTingdianTuifu(tTingdianTuifu));
    }

    /**
     * 修改停电且退服（测试一下，确认后删除此注释）
     */
    @PreAuthorize("@ss.hasPermi('tietasystem:tuifu:edit')")
    @Log(title = "停电且退服（测试一下，确认后删除此注释）", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TTingdianTuifu tTingdianTuifu)
    {
        tTingdianTuifu.setVersion(tTingdianTuifu.getVersion().toString());
        return toAjax(tTingdianTuifuService.updateTTingdianTuifu(tTingdianTuifu));
    }

    /**
     * 删除停电且退服（测试一下，确认后删除此注释）
     */
    @PreAuthorize("@ss.hasPermi('tietasystem:tuifu:remove')")
    @Log(title = "停电且退服（测试一下，确认后删除此注释）", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(tTingdianTuifuService.deleteTTingdianTuifuByIds(ids));
    }

    @Log(title = "停电且退服", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('tietasystem:tuifu:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, String dateRange) throws Exception
    {
        ExcelUtil<TTingdianTuifu> util = new ExcelUtil<TTingdianTuifu>(TTingdianTuifu.class);
        List<TTingdianTuifu> dataList = util.importExcel(file.getInputStream());
        dataList.stream().forEach(m -> {
        	m.setCity(TransData.transCityMap(m.getCity() == null ? "" : m.getCity()));
        });
        String operName = getUsername();
        String depName = getLoginUser().getUser().getDept().getDeptName();
        String userName = getLoginUser().getUser().getUserName();
        String message = "";
        List<TTingdianTuifu> cityDataList = dataList.parallelStream()
                .filter((t)-> {
                    if(!TransData.existCityName(t.getCity()) ) {
                        t.setErrormessage("--地市不能为空或者地市名称不正确--");
                        return true;
                    } else {
                        return false;
                    }
                })
                .collect(Collectors.toList());
        if(cityDataList.size()>0){
            message = "全部数据导入失败，原因为有"+cityDataList.size()+"条记录，地市名称为空或者地市名称不正确！ 请修改后重新导入";
            return AjaxResult.error(message);
        }
        if(depName.contains("辽宁省") || "admin".equals(userName)){
             message = tTingdianTuifuService.importTotal(dataList, operName,dateRange, depName, userName);
        }else{
//            验证id是否为空，是否有否且未加入原因，
            List<TTingdianTuifu> nodataList = dataList.parallelStream()
                    .filter((t)-> {
                        if (t.getId() == null || StringUtils.isEmpty(t.getId().toString()) ) {
                            t.setErrormessage("--id不能为空--");
                            return true;
                        }else if(!TransData.existCityName(t.getCity()) ) {
                            t.setErrormessage("--地市不能为空或者地市名称不正确--");
                            return true;
                        }else if(StringUtils.isNotEmpty(t.getIsFadian())
                                && !StrUtil.equalsAny(t.getIsFadian(),"是","否") ) {
                            t.setErrormessage("--是否发电,内容填写：是/否--");
                            return true;
                        }else if(StringUtils.isNotEmpty(t.getIsneedFaidtian())
                                && !StrUtil.equalsAny(t.getIsneedFaidtian(),"是","否") ){
                            t.setErrormessage("--不需要发电原因,内容填写：是/否--");
                            return true;
                        }else if(("否".equals(t.getIsFadian()) && StringUtils.isEmpty(t.getNoFadianReason())) ){
                            t.setErrormessage("--不发电原因不能为空--");
                            return true;
                        }else if(("否".equals(t.getIsneedFaidtian()) && StringUtils.isEmpty(t.getNoNeedFadianReason())) ){
                            t.setErrormessage("--不需要发电原因不能为空--");
                            return true;
                        } else {
                            return false;
                        }
                    })
                    .collect(Collectors.toList());
            if(nodataList.size()>0){
                message = "全部数据导入失败，有问题的id为：\r\n " + nodataList.stream()
                        .map(t-> t.getId().toString()+":"+t.getErrormessage()+"\r\n")
                        .collect(Collectors.joining(","))
                        +"; \r\n 请修改后重新导入";
                return AjaxResult.error(message);
            }
             message = tTingdianTuifuService.importTotal(dataList, operName, dateRange, depName, userName);
        }
        return AjaxResult.success(message);
    }

    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        ExcelUtil<TTingdianTuifu> util = new ExcelUtil<TTingdianTuifu>(TTingdianTuifu.class);
        return util.importTemplateExcel("退服数据");
    }

}
